package news.paper.tintuc.tinnong.docbao.doctin.adapter;

import java.util.ArrayList;

import news.paper.tintuc.tinnong.docbao.doctin.controller.ApiParams;

import org.json.JSONObject;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Toast;

import com.android.volley.RequestQueue;

public abstract class PaginateAdatper<T extends BaseEntity> extends BaseAdapter {

	protected ArrayList<T> mItems = new ArrayList<T>();
	protected Context context;
	protected int mCurrentPage;
	protected int mPrePage;
	protected int mItemsUntilEndCount;
	protected LayoutInflater mInflater;
	protected Boolean isLoad;
	protected boolean isFirst;
	public PaginateAdatper(Context context) {
		super();
		isFirst=true;
		this.context = context;
		isLoad = true;
		mInflater = (LayoutInflater) context
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		mCurrentPage = 1;
	}

	public void toastLongLength(String text) {
		Toast.makeText(context, text, Toast.LENGTH_LONG).show();
	}

	public void toastShortLength(String text) {
		Toast.makeText(context, text, Toast.LENGTH_SHORT).show();
	}


	public void initData(ArrayList<T> data) {
		mItems = data;
		updateItemsUntilEndCount(data.size());
	}

	@Override
	public int getCount() {
		// TODO Auto-generated method stub
		return mItems.size();
	}
	public T getItemAt(int position){
		return mItems.get(position);
	}
	@Override
	public Object getItem(int position) {
		// TODO Auto-generated method stub
		return mItems.get(position);
	}

	@Override
	public long getItemId(int position) {
		// TODO Auto-generated method stub
		return position;
	}

	public void addItems(ArrayList<T> items) {
		mItems.addAll(items);
	}

	private void updateItemsUntilEndCount(int i) {
		if (mItemsUntilEndCount > 0)
			mItemsUntilEndCount = Math.max(1, i / 4);
		else
			mItemsUntilEndCount = 4;
//		mItemsUntilEndCount=6;
	}

	@Override
	public View getView(int position, View view, ViewGroup group) {
		// TODO Auto-generated method stub
		View viewConveView = getViewByData(position, view, group);
		if (position >= getCount())
			return null;
		if (isLoad && (position >= getCount() - mItemsUntilEndCount)) {
//			requestMoreItemsIfNoRequestExists(mCurrentPage);
		}
		return viewConveView;
	}

	public ArrayList<T> getmItems() {
		return mItems;
	}



	public boolean isDuplicateRequest(int page) {
		return mPrePage == page ? true : false;
	}

	protected abstract View getViewByData(int position, View view,
			ViewGroup group);

	
	protected abstract ApiParams getApiParams(int page);
	protected abstract RequestQueue getRequestQueue();
	
	protected abstract ArrayList<T> getListData(JSONObject json)
			throws Exception;
}
